package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gzhryc.common.DateTools;
import com.gzhryc.common.IDTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.ValidateTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.secruity.VerifyCodeTools;
import com.gzhryc.common.sms.SmsService;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayConfig;
import com.gzhryc.shared_device.common.payment.dao.enums.WXPayConfigEnum;
import com.gzhryc.shared_device.common.payment.services.WXPayConfigService;
import com.gzhryc.shared_device.oem.code.agent.dao.db.Agent;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelation;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.services.AgentBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentReferrerBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentService;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentReferrerBusinessConfigSearch;
import com.gzhryc.shared_device.oem.code.place.dao.db.Clerk;
import com.gzhryc.shared_device.oem.code.place.services.ClerkService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.LoginUserSessionManager;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.WxUserCacheManager;
import com.gzhryc.shared_device.oem.h5.agent.dto.BusinessConfigItem;
import com.gzhryc.shared_device.oem.h5.agent.dto.VerifyCodeData;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.WxJSSDKRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.WxJSSDKResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.security.ResetPwdRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.security.ResetPwdResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.security.SendSMSRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.security.SendSMSResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.security.UserAccountChangeRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.security.UserAccountListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.security.UserBindWXRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.security.UserLoginRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.security.UserLoginResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.security.WxUserLoginRequest;
import com.gzhryc.weixin.gzh.WxAuthorityApi;
import com.gzhryc.weixin.gzh.WxJSSDKApi;
import com.gzhryc.weixin.gzh.WxUserApi;
import com.gzhryc.weixin.gzh.models.JSSDKConfig;
import com.gzhryc.weixin.gzh.msg.Oauth2AccessToken;
import com.gzhryc.weixin.gzh.msg.Oauth2WeixinUser;

public class SecurityController {

	static Logger log = Logger.getLogger(SecurityController.class);

	@Route(value = "/agent/api/v1/login.do")
	public UserLoginResponse login(HttpServletRequest request) {
		UserLoginResponse apiResp = new UserLoginResponse(ClientAPICodeConstants.EXECUTE_ERROR,"登陆失败，请稍后再试");
		UserLoginRequest apiReq = WebUtils.getJsonRequest(request, UserLoginRequest.class);
		if (apiReq != null) {
			String phone = apiReq.getBody().getPhone();
			String loginPwd = apiReq.getBody().getLoginPwd();
			// 如果输入的信息为空 返回错误信息
			if (StringTools.isBlank(phone) || StringTools.isBlank(loginPwd)) {
				apiResp.setMsg("请填写完整的信息");
				return apiResp;
			}
			User user = UserService.self().login(phone, loginPwd);
			if (user == null) {
				apiResp.setMsg("账号密码错误");
				return apiResp;
			}else {
				List<Integer> roleList = null;
				if(StringTools.isNotBlank(apiReq.getBody().getRole())) {
					try {
						String[] arrRole =  URLDecoder.decode(apiReq.getBody().getRole(),"UTF-8").split(",");
						if(arrRole != null && arrRole.length > 0) {
							roleList = new ArrayList<>();
							for(String cc : arrRole) {
								if(StringTools.isNotBlank(cc)){
									Integer roleId = Integer.valueOf(cc);
									if(roleId > 0 && roleId < 9) {
										roleList.add(roleId);
									}
								}
							}
						}
					}catch(Exception e) {
						log.error(e.getMessage(),e);
					}
				}
				try{
					LoginUser loginUser = LoginUserSessionManager.self().loginCheck(user,roleList);
					if(loginUser != null){
						if(LoginUserSessionManager.self().setUserSession(loginUser)) {
							apiResp.setCode(DtoConstants.SUCCESS,null);
							apiResp.getBody().setNickname(user.getNickname());
							apiResp.getBody().setPhone(user.getPhone());
							apiResp.getBody().setRoleType(loginUser.getRoleType());
							apiResp.getBody().setRoleTypeName(ERoleType.note(loginUser.getRoleType()));
							apiResp.getBody().setToken(loginUser.getLoginToken());
							apiResp.getBody().setCanCancelOrder(loginUser.getCanCancelOrder());
							apiResp.getBody().setBusinessTypes(loginUser.getBusinessTypes());
							
							if (loginUser.getParentId() != null) {
								User parent = UserService.self().getById(loginUser.getParentId());
								apiResp.getBody().setSuperiorId(parent.getId());
								apiResp.getBody().setSuperior(parent.getNickname());
							}
						}
					}
				}catch (LogicException e){
					apiResp.setMsg(e.getMessage());
					return apiResp;
				}
			}
		}
		return apiResp;
	}

	@Route(value = "/agent/api/v1/account/list.data")
	public UserAccountListResponse account(HttpServletRequest request){
		UserAccountListResponse apiResp = new UserAccountListResponse(ClientAPICodeConstants.NULL_DATA,"暂无数据");
		LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
		if (loginUser != null) {
			List<UserAccountListResponse.Item> items = new ArrayList<>();
			Agent agent = AgentService.self().getJoinByUserId(loginUser.getId());
			if(agent != null){
				UserAccountListResponse.Item item = new UserAccountListResponse.Item();
				item.setUserId(agent.getUserId());
				item.setUserName(agent.getUser().getNickname());
				item.setRoleType(ERoleType.Agent.index());
				item.setRoleTypeName(ERoleType.Agent.note());
				if(ERoleType.Agent.index().equals(loginUser.getRoleType())){
					item.setState(1);
				}
				items.add(item);
			}
			
			AgentReferrerBusinessConfigSearch search = new AgentReferrerBusinessConfigSearch();
			search.setReferrerUserId(loginUser.getId());
			Long count = AgentReferrerBusinessConfigService.self().countReferrerUserBySearch(search);
			if(count > 0) {
				UserAccountListResponse.Item item = new UserAccountListResponse.Item();
				item.setRoleType(ERoleType.Referrer.index());
				item.setRoleTypeName(ERoleType.Referrer.note());
				if(ERoleType.Referrer.index().equals(loginUser.getRoleType())){
					item.setState(1);
				}
				item.setReferrerCount(count);
				items.add(item);
			}

			List<AgentRelation> agentRelationList = AgentRelationService.self().findByRelationUserId(loginUser.getId());
			if(agentRelationList != null && agentRelationList.size() > 0){
				List<Long> userIds = new ArrayList<>();
				for(AgentRelation agentRelation : agentRelationList){
					userIds.add(agentRelation.getUserId());
				}

				List<User> userList = UserService.self().findByUserIds(userIds);
				if(userList != null && userList.size() > 0) {
					for (AgentRelation agentRelation : agentRelationList) {
						UserAccountListResponse.Item item = new UserAccountListResponse.Item();
						item.setRoleType(agentRelation.getRoleType());
						item.setRoleTypeName(agentRelation.getRoleTypeName());
						item.setSuperiorId(agentRelation.getUserId());

						if(agentRelation.getRoleType().equals(loginUser.getRoleType())){
							if(agentRelation.getUserId().equals(loginUser.getParentId())) {
								item.setState(1);
							}
						}

						for (User user : userList) {
							if (user.getId().equals(agentRelation.getUserId())) {
								item.setSuperior(user.getNickname());
								break;
							}
						}
						items.add(item);
					}
				}
			}
	
			List<Clerk> clerkList = ClerkService.self().findByUserId(loginUser.getId());
			if(clerkList != null && clerkList.size() > 0) {
				List<Long> userIds = new ArrayList<>();
				for(Clerk clerk : clerkList){
					userIds.add(clerk.getMerchantUserId());
				}
				
				List<User> userList = UserService.self().findByUserIds(userIds);
				if(userList != null && userList.size() > 0) {
					for (Clerk clerk : clerkList) {
						UserAccountListResponse.Item item = new UserAccountListResponse.Item();
						item.setRoleType(ERoleType.Clerk.index());
						item.setRoleTypeName(ERoleType.Clerk.note());
						item.setSuperiorId(clerk.getMerchantUserId());

						if(ERoleType.Clerk.index().equals(loginUser.getRoleType())){
							if(clerk.getMerchantUserId().equals(loginUser.getParentId())) {
								item.setState(1);
							}
						}

						for (User user : userList) {
							if (user.getId().equals(clerk.getMerchantUserId())) {
								item.setSuperior(user.getNickname());
								break;
							}
						}
						items.add(item);
					}
				}
			}
	
			if(items.size() > 0){
				apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
				apiResp.getBody().setItems(items);
			}
		}
		return apiResp;
	}

	@Route(value = "/agent/api/v1/account/change.do")
	public UserLoginResponse doChangeAccount(HttpServletRequest request) {
		UserLoginResponse apiResp = new UserLoginResponse(ClientAPICodeConstants.EXECUTE_ERROR, "切换失败");
		UserAccountChangeRequest apiReq = WebUtils.getJsonRequest(request, UserAccountChangeRequest.class);
		if(apiReq != null && apiReq.getBody().getRoleType() != null){
			LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
			if (loginUser != null) {
				User parent = null;
				boolean flag = false;
				if(ERoleType.Agent.index().equals(apiReq.getBody().getRoleType())){
					Agent agent = AgentService.self().getJoinByUserId(loginUser.getId());
					if(agent != null){
						loginUser.setParentId(null);
						loginUser.setRoleType(ERoleType.Agent.index());
						loginUser.setBusinessTypes(null);
						
						List<AgentBusinessConfig> agentbusiConfigList = AgentBusinessConfigService.self().findByUserId(agent.getUserId());
	                	if(agentbusiConfigList != null && agentbusiConfigList.size() > 0) {
	                		loginUser.setBusinessTypes(new ArrayList<>());
	                		for(AgentBusinessConfig busiConfig : agentbusiConfigList) {
	                			BusinessConfigItem item = new BusinessConfigItem();
 	                			item.setBusinessType(busiConfig.getBusinessType());
 	                			item.setEditFeeState(2);	//默认开启
 	                			loginUser.getBusinessTypes().add(item);
	                		}
	                	}
						flag = true;
					}
				}else if(ERoleType.Referrer.index().equals(apiReq.getBody().getRoleType())){
					AgentReferrerBusinessConfigSearch search = new AgentReferrerBusinessConfigSearch();
					search.setReferrerUserId(loginUser.getId());
					Long count = AgentReferrerBusinessConfigService.self().countReferrerUserBySearch(search);
					if(count > 0) {
						loginUser.setParentId(null);
						loginUser.setRoleType(ERoleType.Referrer.index());
						loginUser.setBusinessTypes(null);
						flag = true;
					}
				}else if(apiReq.getBody().getUserId() != null){
					AgentRelation agentRelation = AgentRelationService.self().getJoinByKeys(apiReq.getBody().getUserId(), loginUser.getId());
					if(agentRelation != null){
						loginUser.setRoleType(agentRelation.getRoleType());
						loginUser.setParentId(agentRelation.getUserId());
						loginUser.setBusinessTypes(null);
						parent = UserService.self().getById(agentRelation.getUserId());
						
						if(ERoleType.Partner.index().equals(agentRelation.getRoleType())) {
							List<AgentRelationBusinessConfig> agentbusiConfigList = AgentRelationBusinessConfigService.self()
     	                    		.findByUserKeys(agentRelation.getUserId(),agentRelation.getRelationUserId());
     	                	 if(agentbusiConfigList != null && agentbusiConfigList.size() > 0) {
     	                		loginUser.setBusinessTypes(new ArrayList<>());
     	                		for(AgentRelationBusinessConfig busiConfig : agentbusiConfigList) {
     	                			BusinessConfigItem item = new BusinessConfigItem();
     	                			item.setBusinessType(busiConfig.getBusinessType());
     	                			item.setEditFeeState(busiConfig.getEditFeeState());
     	                			loginUser.getBusinessTypes().add(item);
     	                		}
     	                	 }
                        }
						flag = true;
					}
				}

				if(flag && LoginUserSessionManager.self().setUserSession(loginUser)) {
					apiResp.setCode(DtoConstants.SUCCESS,null);
					apiResp.getBody().setNickname(loginUser.getNickname());
					apiResp.getBody().setPhone(loginUser.getPhone());
					apiResp.getBody().setRoleType(loginUser.getRoleType());
					apiResp.getBody().setRoleTypeName(ERoleType.note(loginUser.getRoleType()));
					apiResp.getBody().setToken(loginUser.getLoginToken());
					apiResp.getBody().setCanCancelOrder(loginUser.getCanCancelOrder());
					apiResp.getBody().setBusinessTypes(loginUser.getBusinessTypes());

					if(parent != null){
						apiResp.getBody().setSuperiorId(parent.getId());
						apiResp.getBody().setSuperior(parent.getNickname());
					}
				}
			}
		}
		return apiResp;
	}

	@Route(value = "/agent/api/v1/resetPwd.do")
	public ResetPwdResponse resetPwd(HttpServletRequest request) {
		ResetPwdResponse apiResp = new ResetPwdResponse(ClientAPICodeConstants.EXECUTE_ERROR);
		ResetPwdRequest apiReq = WebUtils.getJsonRequest(request, ResetPwdRequest.class);
		if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getPhone()) && StringTools.isNotBlank(apiReq.getBody().getPhoneValid())
				&& StringTools.isNotBlank(apiReq.getBody().getPt()) && StringTools.isNotBlank(apiReq.getBody().getLoginPwd())) {
			String phoneValid = apiReq.getBody().getPhoneValid();
			String loginPwd = apiReq.getBody().getLoginPwd();
			if (!ValidateTools.checkPwd(loginPwd)) {
				apiResp.setMsg("密码过于简单，请输入6-12位数字加字母组合");
				return apiResp;
			}
			User user = UserService.self().getByPhone(apiReq.getBody().getPhone());
			if (user != null) {
				String token = user.getPhone() + "_" + apiReq.getBody().getPt();
				VerifyCodeData verifyCodeData = LoginUserSessionManager.self().getVerifyCode(token);
				if (verifyCodeData == null) {
					apiResp.setMsg("请填写正确的手机验证码");
					return apiResp;
				}

				if (DateTools.differenceMinute(verifyCodeData.getCreateDate(), new Date()) > 10) {
					apiResp.setMsg("手机验证码超时");
					return apiResp;
				}

				if (phoneValid.equals(verifyCodeData.getCode())) {
					try {
						if (UserService.self().updateLoginPwd(user.getId(), apiReq.getBody().getLoginPwd())) {
							apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
							LoginUserSessionManager.self().removeVerifyCode(token);
						}
					} catch (LogicException e) {
						apiResp.setMsg(e.getMessage());
					}
				} else {
					apiResp.setMsg("手机验证码不正确");
				}
			}
		}
		return apiResp;
	}

	@Route(value = "/agent/api/v1/sendSMS.do")
	public SendSMSResponse sendSMS(HttpServletRequest request) {
		SendSMSResponse apiResp = new SendSMSResponse(ClientAPICodeConstants.EXECUTE_ERROR,"发送短信失败");
		SendSMSRequest apiReq = WebUtils.getJsonRequest(request, SendSMSRequest.class);
		if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getPhone()) && StringTools.isNotBlank(apiReq.getBody().getCode())
				&& StringTools.isNotBlank(apiReq.getBody().getT()) && StringTools.isNotBlank(apiReq.getBody().getPt())) {
			User user = UserService.self().getByPhone(apiReq.getBody().getPhone());
			if(user != null) {
				log.info("发送短信请求：{{0:json}}", apiReq);
				String code = apiReq.getBody().getCode();
				String t = apiReq.getBody().getT();
				VerifyCodeData verifyCodeData = LoginUserSessionManager.self().getVerifyCode(t);
				if (verifyCodeData != null && verifyCodeData.getCode().equals(code.toUpperCase())) {
					String phoneValid = IDTools.getRandomNumberStr(6);
					VerifyCodeData codeData = new VerifyCodeData();
					codeData.setCode(phoneValid);
					codeData.setCreateDate(new Date());
					String token = user.getPhone() + "_" + apiReq.getBody().getPt();
					codeData.setToken(token);

					if(LoginUserSessionManager.self().setVerifyCodeSession(codeData)) {
						String smsSign = "共享充电";
						if(SmsService.synSendPhoneVerifyCode(user.getPhone(),codeData.getCode(),smsSign)){
							apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
							LoginUserSessionManager.self().removeVerifyCode(t);
						}else{
							log.error("发送短信失败，手机号：{{0}}",user.getPhone());
						}
					}else{
						log.error("缓存手机号验证码失败：内容：{{0:json}}",codeData);
					}
				}else{
					log.error("图片验证码错误，数据：{{0:json}}",verifyCodeData);
					apiResp.setMsg("图片验证码错误");
				}
			}else{
				log.error("未找到用户，手机号：" + apiReq.getBody().getPhone());
			}
		}
		return apiResp;
	}

	@Route(value = "/agent/api/v1/wx/login.do")
	public UserLoginResponse wxLogin(HttpServletRequest request) {
		UserLoginResponse apiResp = new UserLoginResponse(ClientAPICodeConstants.EXECUTE_ERROR, "登陆失败，请稍后再试");
		WxUserLoginRequest apiReq = WebUtils.getJsonRequest(request, WxUserLoginRequest.class);
		if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getAppId()) && StringTools.isNotBlank(apiReq.getBody().getWxCode())) {
			WxAuthorityApi wxAuthorityApi = LoginUserSessionManager.self().getWXAuthorityAPI(apiReq.getBody().getAppId());
			if(wxAuthorityApi != null) {
				Oauth2AccessToken oauth2AccessToken = wxAuthorityApi.getOauth2AccessToken(apiReq.getBody().getWxCode());
				if (oauth2AccessToken != null) {
					log.info("获取微信AccessToken信息：{{0:json}}",oauth2AccessToken);
					User user = UserService.self().getByExId(apiReq.getBody().getAppId(),oauth2AccessToken.getOpenid());
					if(user == null) {
						WxUserApi wxUserApi = LoginUserSessionManager.self().getWXUserAPI(apiReq.getBody().getAppId());
						Oauth2WeixinUser oauth2WxUser = wxUserApi.getWeixinUser(oauth2AccessToken);
						if(oauth2WxUser != null) {
							WxUserCacheManager.self().save(apiReq.getBody().getAppId(), apiReq.getBody().getWxCode(),oauth2WxUser);
						}
					}else{
						List<Integer> roleList = null;
						if(StringTools.isNotBlank(apiReq.getBody().getRole())) {
							try {
								String[] arrRole = URLDecoder.decode(apiReq.getBody().getRole(),"UTF-8").split(",");
								if(arrRole != null && arrRole.length > 0) {
									roleList = new ArrayList<>();
									for(String cc : arrRole) {
										if(StringTools.isNotBlank(cc)){
											Integer roleId = Integer.valueOf(cc);
											if(roleId > 0 && roleId < 9) {
												roleList.add(roleId);
											}
										}
									}
								}
							}catch(Exception e) {
								log.error(e.getMessage(), e);
							}
						}
						try {
							LoginUser loginUser = LoginUserSessionManager.self().loginCheck(user, roleList);
							if (loginUser != null) {
								if (LoginUserSessionManager.self().setUserSession(loginUser)) {
									apiResp.setCode(DtoConstants.SUCCESS, null);
									apiResp.getBody().setNickname(user.getNickname());
									apiResp.getBody().setPhone(user.getPhone());
									apiResp.getBody().setRoleType(loginUser.getRoleType());
									apiResp.getBody().setRoleTypeName(ERoleType.note(loginUser.getRoleType()));
									apiResp.getBody().setToken(loginUser.getLoginToken());
									apiResp.getBody().setCanCancelOrder(loginUser.getCanCancelOrder());
									apiResp.getBody().setBusinessTypes(loginUser.getBusinessTypes());

									if (loginUser.getParentId() != null) {
										User parent = UserService.self().getById(loginUser.getParentId());
										apiResp.getBody().setSuperiorId(parent.getId());
										apiResp.getBody().setSuperior(parent.getNickname());
									}
								}
							}
						} catch (LogicException e) {
							apiResp.setMsg(e.getMessage());
							return apiResp;
						}
					}
				}else{
					log.error("微信登陆：{{0:json}}",apiReq);
					log.error("获取微信Oauth2AccessToken失败，无返回");
				}
			}else {
				log.error("微信登陆：{{0:json}}",apiReq);
				log.error("获取微信API服务失败");
			}
		}
		return apiResp;
	}

	@Route(value = "/agent/api/v1/wx/bind.do")
	public UserLoginResponse wxBind(HttpServletRequest request) {
		UserLoginResponse apiResp = new UserLoginResponse(ClientAPICodeConstants.EXECUTE_ERROR, "绑定微信失败");
		UserBindWXRequest apiReq = WebUtils.getJsonRequest(request, UserBindWXRequest.class);
		log.info("绑定微信：{{0:json}}",apiReq);
		if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getPhoneValid())
				&& StringTools.isNotBlank(apiReq.getBody().getPt()) && StringTools.isNotBlank(apiReq.getBody().getPhone())
				&& StringTools.isNotBlank(apiReq.getBody().getAppId()) && StringTools.isNotBlank(apiReq.getBody().getWxCode())) {
			Oauth2WeixinUser oauth2WxUser = WxUserCacheManager.self().get(apiReq.getBody().getAppId(),apiReq.getBody().getWxCode());
			if(oauth2WxUser == null) {
				WxAuthorityApi wxAuthorityApi = LoginUserSessionManager.self().getWXAuthorityAPI(apiReq.getBody().getAppId());
				if (wxAuthorityApi != null) {
					Oauth2AccessToken oauth2AccessToken = wxAuthorityApi.getOauth2AccessToken(apiReq.getBody().getWxCode());
					if (oauth2AccessToken != null) {
						WxUserApi wxUserApi = LoginUserSessionManager.self().getWXUserAPI(apiReq.getBody().getAppId());
						oauth2WxUser = wxUserApi.getWeixinUser(oauth2AccessToken);
					} else {
						log.error("获取微信Oauth2AccessToken失败，wxCode = {{0}}", apiReq.getBody().getWxCode());
					}
				} else {
					log.error("获取微信服务失败，APPID = {{0}}", apiReq.getBody().getAppId());
				}
			}

			if (oauth2WxUser == null) {
				apiResp.setMsg("未能获取微信信息，请退出重新尝试");
				return apiResp;
			}
			log.info("获取微信用户信息：{{0:json}}", oauth2WxUser);
			log.info("请求信息：{{0:json}}", apiReq);

			String phoneValid = apiReq.getBody().getPhoneValid();
			String validToken = apiReq.getBody().getPhone() + "_" + apiReq.getBody().getPt();
			VerifyCodeData verifyCodeData = LoginUserSessionManager.self().getVerifyCode(validToken);
			if(verifyCodeData == null){
				apiResp.setMsg("请填写正确的手机验证码");
				return apiResp;
			}

			if(DateTools.differenceMinute(verifyCodeData.getCreateDate(),new Date()) > 10){
				apiResp.setMsg("手机验证码超时");
				return apiResp;
			}

			if(phoneValid.equals(verifyCodeData.getCode())){
				User user = UserService.self().getByPhone(apiReq.getBody().getPhone());
				if(user != null) {
					User updateEntity = new User();
					updateEntity.setId(user.getId());
					updateEntity.setAppId(apiReq.getBody().getAppId());
					updateEntity.setNickname(oauth2WxUser.getNickname());
					updateEntity.setOpenId(oauth2WxUser.getOpenid());
					try {
						if(UserService.self().updateNotNull(updateEntity)){
							List<Integer> roleList = null;
							if(StringTools.isNotBlank(apiReq.getBody().getRole())) {
								try {
									String[] arrRole = URLDecoder.decode(apiReq.getBody().getRole(),"UTF-8").split(",");
									if(arrRole != null && arrRole.length > 0) {
										roleList = new ArrayList<>();
										for(String cc : arrRole) {
											if(StringTools.isNotBlank(cc)){
												Integer roleId = Integer.valueOf(cc);
												if(roleId > 0 && roleId < 9) {
													roleList.add(roleId);
												}
											}
										}
									}
								}catch(Exception e) {
									log.error(e.getMessage(), e);
								}
							}
							try {
								LoginUser loginUser = LoginUserSessionManager.self().loginCheck(user, roleList);
								if (loginUser != null) {
									if (LoginUserSessionManager.self().setUserSession(loginUser)) {
										apiResp.setCode(DtoConstants.SUCCESS, null);
										apiResp.getBody().setNickname(user.getNickname());
										apiResp.getBody().setPhone(user.getPhone());
										apiResp.getBody().setRoleType(loginUser.getRoleType());
										apiResp.getBody().setRoleTypeName(ERoleType.note(loginUser.getRoleType()));
										apiResp.getBody().setToken(loginUser.getLoginToken());
										apiResp.getBody().setCanCancelOrder(loginUser.getCanCancelOrder());
										apiResp.getBody().setBusinessTypes(loginUser.getBusinessTypes());

										if (loginUser.getParentId() != null) {
											User parent = UserService.self().getById(loginUser.getParentId());
											apiResp.getBody().setSuperiorId(parent.getId());
											apiResp.getBody().setSuperior(parent.getNickname());
										}
									}
								}
							} catch (LogicException e) {
								apiResp.setMsg(e.getMessage());
								return apiResp;
							}
						}
					} catch (LogicException e) {
						apiResp.setMsg(e.getMessage());
					}
				}else{
					apiResp.setMsg("用户不存在");
				}
			}else{
				log.error("验证码不正确，缓存验证码：{{0}}，请求验证码：{{1}}",verifyCodeData.getCode(),phoneValid);
				apiResp.setMsg("手机验证码不正确");
			}
		}
		return apiResp;
	}

	@Route(value = "/agent/api/v1/verifyCode.jpeg")
	public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
		Integer width = WebUtils.getInteger(request, "w", 250);
		Integer height = WebUtils.getInteger(request, "h", 50);
		String t = WebUtils.getString(request, "t");
		if(StringTools.isNotBlank(t) && t.length() > 10) {
			VerifyCodeTools.VerifyCode verifyCode = VerifyCodeTools.createImg(width, height, 5);
			VerifyCodeData codeData = new VerifyCodeData();
			codeData.setCode(verifyCode.getCode());
			codeData.setCreateDate(new Date());
			codeData.setToken(t);
			LoginUserSessionManager.self().setVerifyCodeSession(codeData);
			WebUtils.exportJPEG(response, verifyCode.getImg());
			
			log.info("创建图片验证码：{{0:json}}", codeData);
		}
	}

	@Route(value = {"/agent/api/v1/wx/jssdk/get.do"}, method = "POST")
	public WxJSSDKResponse getWxJSSDK(HttpServletRequest request) {
		WxJSSDKResponse result = new WxJSSDKResponse(ClientAPICodeConstants.EXECUTE_ERROR, "获取JSSDK失败");
		WxJSSDKRequest apiReq = WebUtils.getJsonRequest(request, WxJSSDKRequest.class);
		if (apiReq == null || StringTools.isBlank(apiReq.getBody().getAppId()) || StringTools.isBlank(apiReq.getBody().getUrl())) {
			result.setMsg("参数不正确");
			return result;
		}
		
		String appId = apiReq.getBody().getAppId();
		if(StringTools.isBlank(appId)) {
			//获取默认公众号
			WXPayConfig wxpayConfig = WXPayConfigService.self().getDef(WXPayConfigEnum.AppType.wxgzh.index());
			if(wxpayConfig != null) {
				appId = wxpayConfig.getAppId();
			}
		}

		log.info("获取公众号JS配置请求：{{0:json}}",apiReq);

		WxJSSDKApi wxJSSDKApi = LoginUserSessionManager.self().getWxJSSDKApi(appId);
		if(wxJSSDKApi != null) {
			JSSDKConfig jsConfig = wxJSSDKApi.getConfig(apiReq.getBody().getUrl());
			if(jsConfig != null){
				result.getBody().setConfig(jsConfig);
				result.setCode(ClientAPICodeConstants.SUCCESS, null);
			}
		}else{
			log.error("未获取公众号服务，APPID：" + apiReq.getBody().getAppId());
		}
		return result;
	}

}
